package utils

import (
	"encoding/json"
	"os"
	"path/filepath"
	"strings"

	"gopkg.in/yaml.v3"
)

func IsPackage() bool {
	exePath, _ := os.Executable()
	fileName := filepath.Base(exePath)

	return !strings.HasPrefix(fileName, "__debug_")
}

func LoadYamlError(path string, data interface{}, f func(error)) error {
	content, err := os.ReadFile(path)
	if err != nil {
		return err
	}

	err = yaml.Unmarshal(content, data)
	if err != nil {
		f(err)
		return err
	}

	return nil
}

func LoadJsonError(path string, data interface{}, f func(error)) error {
	content, err := os.ReadFile(path)
	if err != nil {
		return err
	}
	err = json.Unmarshal(content, data)
	if err != nil {
		f(err)
		return err
	}

	return nil
}

func TryCatch(exec func(), errfunc func()) {
	func() {
		defer func() {
			if err := recover(); err != nil {
				errfunc()
			}
		}()

		exec()

	}()
}
